package com.xyht.sca_s.student_manage_system.modules.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xyht.sca_s.student_manage_system.auth.util.JwtTokenUtil;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ExceptionCast;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.CacheUtil;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgStructureMapper;
import com.xyht.sca_s.student_manage_system.modules.teacher.entity.SmsTeacherInfo;
import com.xyht.sca_s.student_manage_system.modules.teacher.entity.SmsUserTeacherRelation;
import com.xyht.sca_s.student_manage_system.modules.teacher.entity.resp.SmsTeacherInfoResp;
import com.xyht.sca_s.student_manage_system.modules.teacher.mapper.SmsTeacherInfoMapper;
import com.xyht.sca_s.student_manage_system.modules.teacher.mapper.SmsUserTeacherRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.user.entity.ChangeUserPassword;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.entity.VerifyCode;
import com.xyht.sca_s.student_manage_system.modules.user.entity.req.SmsUserLoginReq;
import com.xyht.sca_s.student_manage_system.modules.user.entity.req.WxLoginReq;
import com.xyht.sca_s.student_manage_system.modules.user.entity.req.WxMpMessagePushReq;
import com.xyht.sca_s.student_manage_system.modules.user.entity.resp.SmsSearchUserResp;
import com.xyht.sca_s.student_manage_system.modules.user.entity.resp.SmsUserResp;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import com.xyht.sca_s.student_manage_system.modules.user.service.SmsUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.modules.user.util.FormatUtil;
import com.xyht.sca_s.student_manage_system.modules.user.util.SMSUtil;
import com.xyht.sca_s.student_manage_system.modules.wx.util.WeChatUtil;
import com.xyht.sca_s.student_manage_system.modules.user.util.verify_code.VerifyCodeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.AccountIsUseConstant.ACCOUNT_CAN_NOT_USE;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.IsBindFlag.IS_BIND_FALSE;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.IsBindFlag.IS_BIND_TRUE;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.IsMessageFlag.IS_MESSAGE_CLOSE;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.IsMessageFlag.IS_MESSAGE_OPEN;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.IsSameUserFlag.IS_SAME_USER_FALSE;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.IsSameUserFlag.IS_SAME_USER_TRUE;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.TeacherAndStudentFlag.TEACHER_FLAG;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2022-11-27
 */
@Service
public class SmsUserServiceImpl extends ServiceImpl<SmsUserMapper, SmsUser> implements SmsUserService {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private SmsUserMapper smsUserMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private SmsUserTeacherRelationMapper smsUserTeacherRelationMapper;
    @Autowired
    private SmsTeacherInfoMapper smsTeacherInfoMapper;
    @Autowired
    private WeChatUtil weChatUtil;
    @Resource
    private SmsOrgStructureMapper smsOrgStructureMapper;


    @Override
    public ResponseResult webLogin(SmsUserLoginReq smsUserLoginReq) {
        List<SmsUser> smsUserList = new ArrayList<>();
        if (isNullOrEmpty(smsUserLoginReq.getLoginName()) || isNullOrEmpty(smsUserLoginReq.getPassword())
                || isNullOrEmpty(smsUserLoginReq.getCode()) || isNullOrEmpty(smsUserLoginReq.getUid())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        String code = smsUserLoginReq.getCode().toUpperCase();
        String uid = smsUserLoginReq.getUid();
        //验证码校验
        String cacheCode = cacheUtil.getObject(uid, String.class);
        if (cacheCode == null || !cacheCode.equals(code)) {
            return CommonResult.failed(CommonCodeEnum.VERIFY_CODE_CHECK_FAIL);
        }

        //账号密码校验
        //身份证校验
        if (smsUserLoginReq.getLoginName().length() == 18) {
            SmsTeacherInfo smsTeacherInfo = smsTeacherInfoMapper.selectOne(new QueryWrapper<SmsTeacherInfo>()
                    .lambda()
                    .eq(SmsTeacherInfo::getTchIdCard, smsUserLoginReq.getLoginName()));
            if (smsTeacherInfo != null) {
                SmsUserTeacherRelation userTeacherRelation = smsUserTeacherRelationMapper.selectOne(new QueryWrapper<SmsUserTeacherRelation>()
                        .lambda()
                        .eq(SmsUserTeacherRelation::getTchId, smsTeacherInfo.getId()));
                if (userTeacherRelation != null) {
                    SmsUser smsUser = smsUserMapper.selectById(userTeacherRelation.getUserId());
                    if (smsUser != null) {
                        smsUserList.add(smsUser);
                    }
                }
            }
        } else {
            QueryWrapper<SmsUser> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.lambda().eq(SmsUser::getUsername, smsUserLoginReq.getLoginName())
                    .or().eq(SmsUser::getTel, smsUserLoginReq.getLoginName());
            smsUserList = smsUserMapper.selectList(userQueryWrapper);
        }
        if (smsUserList == null || smsUserList.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        if (smsUserList.size() > 1) {
            return CommonResult.failed(CommonCodeEnum.ACCOUNT_ERR);
        }
        SmsUser smsUser = smsUserList.get(0);
        if (!smsUser.getPassword().equals(smsUserLoginReq.getPassword())) {
            return CommonResult.failed(CommonCodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }
//        if (smsUser.getIsUse() == ACCOUNT_CAN_NOT_USE) {
//            return CommonResult.failed(CommonCodeEnum.ACCOUNT_CAN_NOT_USE);
//        }
        //缓存用户权限
        cacheUtil.saveUserAuthorization(smsUser.getId());

        SmsUserResp smsUserResp = new SmsUserResp();
        BeanUtils.copyProperties(smsUser, smsUserResp);
        String token = jwtTokenUtil.generateToken(smsUser.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("tokenHead", tokenHead);
        map.put("user", smsUserResp);
        return CommonResult.success(map);
    }

    @Override
    public ResponseResult wxLogin(SmsUserLoginReq smsUserLoginReq) {
        if (smsUserLoginReq.getTestFlag() != 1) {
            if (isNullOrEmpty(smsUserLoginReq.getCode())) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
        }

        if (isNullOrEmpty(smsUserLoginReq.getLoginName()) || isNullOrEmpty(smsUserLoginReq.getPassword())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        QueryWrapper<SmsUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.lambda().eq(SmsUser::getUsername, smsUserLoginReq.getLoginName())
                .or().eq(SmsUser::getTel, smsUserLoginReq.getLoginName());
        List<SmsUser> smsUserList = smsUserMapper.selectList(userQueryWrapper);
        if (smsUserList == null || smsUserList.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        if (smsUserList.size() > 1) {
            return CommonResult.failed(CommonCodeEnum.ACCOUNT_ERR);
        }
        SmsUser smsUser = smsUserList.get(0);
        if (!smsUser.getPassword().equals(smsUserLoginReq.getPassword())) {
            return CommonResult.failed(CommonCodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }
//        if (smsUser.getIsUse() == ACCOUNT_CAN_NOT_USE) {
//            return CommonResult.failed(CommonCodeEnum.ACCOUNT_CAN_NOT_USE);
//        }
        //缓存用户权限
        cacheUtil.saveUserAuthorization(smsUser.getId());

        SmsUserResp smsUserResp = new SmsUserResp();
        BeanUtils.copyProperties(smsUser, smsUserResp);
        String token = jwtTokenUtil.generateToken(smsUser.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("tokenHead", tokenHead);
        if (smsUserLoginReq.getTestFlag() != 1) {
            try {
                WxMaJscode2SessionResult sessionResult = weChatUtil.getSessionKey(wxMaService, smsUserLoginReq.getCode());
                String openId = sessionResult.getOpenid();
                String sessionKey = sessionResult.getSessionKey();
                if (openId.isEmpty() || sessionKey.isEmpty()) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.WX_CHECK_FAIL));
                }
                if (smsUser.getWxId() != null && smsUser.getWxId().equals(openId)) {
                    smsUserResp.setIsSameWXUser(IS_SAME_USER_TRUE);
                } else {
                    smsUserResp.setIsSameWXUser(IS_SAME_USER_FALSE);
                }
            } catch (Exception e) {
                e.printStackTrace();
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.WX_CHECK_FAIL));
            }
        }
        map.put("user", smsUserResp);
        return CommonResult.success(map);
    }

    @Override
    public ResponseResult wxLoginCheck(WxLoginReq wxLoginReq) {
        if (isNullOrEmpty(wxLoginReq.getCode())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        HashMap<String, Object> wxMap = new HashMap<>();
        try {
            int is_register = 0;
            WxMaJscode2SessionResult sessionResult = weChatUtil.getSessionKey(wxMaService, wxLoginReq.getCode());
            String openId = sessionResult.getOpenid();
            String sessionKey = sessionResult.getSessionKey();
            if (openId.isEmpty() || sessionKey.isEmpty()) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.WX_CHECK_FAIL));
            }

            QueryWrapper<SmsUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SmsUser::getWxId, openId);
            SmsUser user = smsUserMapper.selectOne(queryWrapper);
            if (user == null) {
                wxMap.put("openID", openId);
                wxMap.put("sessionKey", sessionKey);
                wxMap.put("is_register", is_register);
            } else {
                is_register = 1;
//                if (user.getIsUse() == ACCOUNT_CAN_NOT_USE) {
//                    return CommonResult.failed(CommonCodeEnum.ACCOUNT_CAN_NOT_USE);
//                }
                //缓存用户权限
                cacheUtil.saveUserAuthorization(user.getId());

                SmsUserResp smsUserResp = new SmsUserResp();
                BeanUtils.copyProperties(user, smsUserResp);
                String token = jwtTokenUtil.generateToken(user.getId());
                wxMap.put("token", token);
                wxMap.put("tokenHead", tokenHead);
                wxMap.put("user", smsUserResp);
                wxMap.put("openID", openId);
                wxMap.put("sessionKey", sessionKey);
                wxMap.put("is_register", is_register);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.WX_CHECK_FAIL));
        }

        return CommonResult.success(wxMap);
    }

    @Override
    public ResponseResult wxUnBindUser(WxLoginReq wxLoginReq, String user_id) {
        ResponseResult result = CommonResult.failed(CommonCodeEnum.WX_UNBIND_FAIL);
        if (isNullOrEmpty(wxLoginReq.getCode())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        try {
            WxMaJscode2SessionResult sessionResult = weChatUtil.getSessionKey(wxMaService, wxLoginReq.getCode());
            String openId = sessionResult.getOpenid();
            String sessionKey = sessionResult.getSessionKey();
            if (openId.isEmpty() || sessionKey.isEmpty()) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.WX_UNBIND_FAIL));
            }

            SmsUser smsUser = smsUserMapper.selectById(user_id);
            if (!smsUser.getWxId().equals(openId)) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.WX_UNBIND_FAIL));
            }
            if (smsUser.getIsBind() == IS_BIND_FALSE) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.WX_UNBIND_FAIL));
            }
            if (smsUser.getBindTimes() > 100) { //换绑三次后无法换绑
                result = CommonResult.failed(CommonCodeEnum.WX_BIND_OVER_LIMIT);
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.WX_BIND_OVER_LIMIT));
            }

            SmsUser user = new SmsUser();
            user.setId(user_id);
            user.setWxId("");
            user.setWxMpId("");
            user.setWxUnionId("");
            user.setIsMessage(IS_MESSAGE_CLOSE);
            user.setIsBind(IS_BIND_FALSE);
            user.setIsMpBind(IS_BIND_FALSE);
            smsUserMapper.updateById(user);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionCast.cast(result);
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult wxBindUser(WxLoginReq wxLoginReq, String user_id) {
        if (isNullOrEmpty(wxLoginReq.getCode())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        try {
            WxMaJscode2SessionResult sessionResult = weChatUtil.getSessionKey(wxMaService, wxLoginReq.getCode());
            String openId = sessionResult.getOpenid();
            String sessionKey = sessionResult.getSessionKey();
            String unionID = sessionResult.getUnionid();
            if (openId.isEmpty() || sessionKey.isEmpty()) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.WX_BIND_FAIL));
            }

            SmsUser smsUser = smsUserMapper.selectById(user_id);
            if (smsUser.getIsBind() == IS_BIND_TRUE) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.WX_BIND_FAIL));
            }
            Integer times = smsUser.getBindTimes();

            SmsUser user = new SmsUser();
            user.setId(user_id);
            user.setWxId(openId);
            user.setWxUnionId(unionID);
            user.setIsBind(IS_BIND_TRUE);
            user.setBindTimes(times + 1);
            smsUserMapper.updateById(user);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.WX_BIND_FAIL));
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult getPersonInfo(String user_id) {
        SmsUser user = cacheUtil.getCatchUserInfo(user_id);
        if (user == null) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_EXIST);
        }
        SmsUserResp userResp = new SmsUserResp();
        BeanUtils.copyProperties(user, userResp);
        Map<String, Object> map = new HashMap<>();
        map.put("userInfo", userResp);

        return CommonResult.success(map);
    }

    @Override
    public ResponseResult getUserInfo(String user_id) {
        SmsUser user = cacheUtil.getCatchUserInfo(user_id);
        if (user == null) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_EXIST);
        }
        SmsUserResp userResp = new SmsUserResp();
        BeanUtils.copyProperties(user, userResp);
        return CommonResult.success(userResp);
    }

    @Override
    public ResponseResult updateUserPic(String user_id, String user_pic) {
        if (isNullOrEmpty(user_pic)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsUser smsUser = new SmsUser();
        smsUser.setId(user_id);
        smsUser.setUserPic(user_pic);
        int result = smsUserMapper.updateById(smsUser);
        if (result == 0) {
            return CommonResult.failed(CommonCodeEnum.UPDATE_FAIL);
        }
        cacheUtil.saveUserInfo(user_id);
        return CommonResult.success();
    }

    @Override
    @Transactional
    public ResponseResult userChangePasswordByVerifyCode(ChangeUserPassword entity) {
        if (isNullOrEmpty(entity.getCode()) || isNullOrEmpty(entity.getPhone_num())
                || isNullOrEmpty(entity.getNew_password())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        String codeTel = "CP_" + entity.getPhone_num();
        //TODO 对比code VERIFY_CODE_CHECK_FAIL
        String resultCode = cacheUtil.getObject(codeTel, String.class);
        if (resultCode == null || !resultCode.equals(entity.getCode())) {
            return CommonResult.failed(CommonCodeEnum.VERIFY_CODE_CHECK_FAIL);
        }
        //清除已使用验证码
        cacheUtil.delete(codeTel);

        List<SmsUser> userList = smsUserMapper.selectList(new QueryWrapper<SmsUser>()
                .lambda().eq(SmsUser::getTel, entity.getPhone_num()));
        if (userList == null || userList.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.TEL_NOT_BIND);
        }

        SmsUser smsUser = new SmsUser();
        smsUser.setPassword(entity.getNew_password());
        int result = smsUserMapper.update(smsUser, new QueryWrapper<SmsUser>()
                .lambda()
                .eq(SmsUser::getTel, entity.getPhone_num()));
        if (result == 0) {
            return CommonResult.failed(CommonCodeEnum.UPDATE_FAIL);
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult userChangePasswordByOldPassword(String user_id, ChangeUserPassword changeUserPassword) {
        if (isNullOrEmpty(changeUserPassword.getNew_password()) || isNullOrEmpty(changeUserPassword.getOld_password())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        if (changeUserPassword.getNew_password().equals(changeUserPassword.getOld_password())) {
            return CommonResult.failed(CommonCodeEnum.OLD_PASSWORD_LIKE_NEW_PASSWORD);
        }
        SmsUser smsUser = smsUserMapper.selectById(user_id);
        if (smsUser == null) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_EXIST);
        }
        if (!smsUser.getPassword().equals(changeUserPassword.getOld_password())) {
            return CommonResult.failed(CommonCodeEnum.OLD_PASSWORD_ERROR);
        }
        //TODO  md5加密
        SmsUser newUser = new SmsUser();
        newUser.setId(user_id);
        newUser.setPassword(changeUserPassword.getNew_password());
        int result = smsUserMapper.updateById(newUser);
        if (result == 0) {
            return CommonResult.failed(CommonCodeEnum.UPDATE_FAIL);
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult phoneVerifyCode(String phoneNum) {
        //TODO 1分钟内同个手机号不能再次发送
        if (isNullOrEmpty(phoneNum)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        if (!FormatUtil.phoneFormat(phoneNum)) {
            return CommonResult.failed(CommonCodeEnum.TEL_FORMAT_ERROR);
        }
        String checkTel = "CP_" + phoneNum;
        if (cacheUtil.hasKey(checkTel)) {
            return CommonResult.failed(CommonCodeEnum.CODE_GET_FAIL);
        }

        List<SmsUser> userList = smsUserMapper.selectList(new QueryWrapper<SmsUser>()
                .lambda().eq(SmsUser::getTel, phoneNum));
        if (userList == null || userList.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.TEL_NOT_BIND);
        }
//        SmsUser smsUser = smsUserMapper.selectById(user_id);
//        if (smsUser == null) {
//            return CommonResult.failed(CommonCodeEnum.USER_NOT_EXIST);
//        }
//        if (isNullOrEmpty(smsUser.getTel())){
//            return CommonResult.failed(CommonCodeEnum.TEL_NOT_BIND);
//        }
//        if (!smsUser.getTel().equals(phoneNum)){
//            return CommonCodeEnum.TEL_BIND_ERROR;
//        }
        VerifyCodeUtil verifyCodeUtil = new VerifyCodeUtil();
        VerifyCode verifyCode = verifyCodeUtil.generateStr(80, 28);
        String code = verifyCode.getCode();
        //TODO 发送短信 保存code
        try {
            Boolean bl = SMSUtil.sendSMSCode(phoneNum, code);
            if (!bl) {
                return CommonResult.failed(CommonCodeEnum.CODE_OVERFLOW);
            }
            cacheUtil.add(checkTel, code, 5, TimeUnit.MINUTES);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FAIL);
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult searchUser(String search_str) {
        if (isNullOrEmpty(search_str)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        List<SmsSearchUserResp> smsUserList = smsUserMapper.selectList(new QueryWrapper<SmsUser>()
                        .lambda()
                        .like(SmsUser::getRealName, search_str)
                        .eq(SmsUser::getFlag, TEACHER_FLAG))
                .stream()
                .map(user -> {
                    SmsSearchUserResp smsSearchUserResp = new SmsSearchUserResp();
                    BeanUtils.copyProperties(user, smsSearchUserResp);

                    List<String> orgNameList = smsOrgStructureMapper.getOrgNameByUser(user.getId());
                    smsSearchUserResp.setOrgNameList(orgNameList);
                    return smsSearchUserResp;
                })
                .collect(Collectors.toList());
        return CommonResult.success(smsUserList);
    }

    @Override
    public ResponseResult wxMpMessagePushSwitch(WxMpMessagePushReq req, String user_id) {
        if (isNullOrEmpty(req.getIsMessage()) || req.getIsMessage() > IS_MESSAGE_OPEN) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsUser smsUser = cacheUtil.getUserInfo(user_id);
        if (smsUser.getIsMpBind() == IS_BIND_FALSE) {
            return CommonResult.failed(CommonCodeEnum.WX_MP_NOT_BIND);
        }

        if (req.getIsMessage() == IS_MESSAGE_OPEN) {
            if (isNullOrEmpty(smsUser.getWxMpId())) {
                return CommonResult.failed(CommonCodeEnum.WX_MP_NOT_BIND);
            }
        }

        SmsUser updateUser = new SmsUser();
        updateUser.setId(smsUser.getId());
        updateUser.setIsMessage(req.getIsMessage());
        smsUserMapper.updateById(updateUser);

        cacheUtil.saveUserInfo(smsUser.getId());
        return CommonResult.success();
    }
}
